import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:dmz/business/mine/model/repair_model.dart';
import 'package:dmz/business/mine/widget/seting_repair_widgets.dart';
import 'package:dmz/utils/customize_loding.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_rx/get_rx.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart' as picker;

import '../../../base/controller/base_controller.dart';
import '../../../request/apis.dart';
import '../../../request/request_client.dart';
import '../../../routers/routers.dart';
import '../../../tools/map/map_manger.dart';
import '../../../utils/oss_utils.dart';
import '../../../utils/sp_utils.dart';
import '../../home/controller/home_main_controller.dart';
import '../../home/model/moto_model.dart';
import '../../home/model/serve_point.dart';
import '../../home/widgets/run_message_widgets.dart';
import '../../home/widgets/shanre_details_widgets.dart';

class SetingRepairController extends BaseController {
  @override
  void loadNet() {}

  @override
  void onHidden() {}

  @override
  void onInit() {
    var motoList = Get.find<HomePageController>().motoList;
    var motoSelect = Get.find<HomePageController>().pageIndex;
    selectData = motoList[motoSelect];
    addRepairContent[0] = selectData.name!;
    addRepairContent[2] = updataTime = SPUtils.getTimeStr();
    getListData(1, 0);
    super.onInit();
  }

  List<String> addRepairContent = ['', '', '2024-05-27'];
  TextEditingController addNewCT = TextEditingController();
  List<picker.AssetEntity> imagesDatas = [];
  late MotoModel selectData;
  List<ServePoint> pointList = [];
  ServePoint? selectPoint;
  int opintSelNum = -1;
  int opintSelTypeNum = -1;
  String updataTime = '';
  Map<String, dynamic>? parameters;
  List<List<RepairModel>> pagedatas = [[], [], [], []];
  PageController pageController = PageController();
  RxInt pageIndex = 0.obs;

  changePage(index) {
    if (pagedatas[index].isEmpty) {
      getListData(1, index);
    }
    pageIndex.value = index;
    pageController.jumpToPage(index);
  }

  getListData(int index, int tag, {bool isAdd = false}) async {
    await RequestClient().post<RepairPageModel>(APIS.repairList, data: {
      'index': index,
      'size': 20,
      if (tag != 0) 'status': tag - 1
    }).then((value) {
      if (value != null) {
        isAdd
            ? pagedatas[tag].addAll(value.list ?? [])
            : pagedatas[tag] = value.list ?? [];
        update(['repair$tag']);
      }
    });
  }

  addNewRepair() {
    getMotoLocation();
    Get.toNamed(RouteGet.repairAdd);
  }

  selectImages() async {
    List<picker.AssetEntity>? result = await picker.AssetPicker.pickAssets(
      Get.context!,
      pickerConfig: picker.AssetPickerConfig(maxAssets: 6 - imagesDatas.length),
    );
    if (result != null && result.isNotEmpty) {
      imagesDatas.addAll(result);
      update(['addRepair']);
    }
  }

  cleanSelect(int index) {
    imagesDatas.removeAt(index);
    update(['addRepair']);
  }

  ///上传数据
  updataNewRepair() async {
    if (selectPoint == null) {
      EMILoding.hitLoding('请选择报修网点'.tr);
      return;
    }
    EMILoding.didLoding();
    await OssUtils.initOss();
    List<List<int>> result = [];
    for (var element in imagesDatas) {
      var data = await element.originBytes;
      if (data != null) result.add(data);
    }
    parameters ??= {};
    parameters?['ebike_id'] = selectData.id;
    parameters?['desc'] = addNewCT.text;

    // parameters[] = {'ebike_id': selectData.id, 'desc': addNewCT.text};
    if (result.isNotEmpty && parameters?['photo'] == null) {
      var imageStrs = await OssUtils.updataMoreImages(result);
      parameters?['photo'] = imageStrs;
    }

    parameters?['store_id'] = selectPoint?.id;

    RequestClient()
        .post<Map<String, dynamic>>(APIS.repairCreate, data: parameters)
        .then((value) async {
      EMILoding.hitLoding('上报成功'.tr, isScuess: true);
      getListData(1, pageIndex.value);
      Get.back();
    });
  }

  addTopSelect(int tag) {
    switch (tag) {
      case 0:
        Get.toNamed(RouteGet.selectMoto);
        break;
      case 1:
        opintSelTypeNum = opintSelNum;
        EMILoding.showBottomWindow(
            ShareDetailsWidgets.widowBackWidget(
                '网点服务'.tr,
                SetRepairWidgets.selectSeverPointWidget(
                    pointList, () => selectSeverPoint())),
            isDismissible: true,
            showBack: true);
        break;
      case 2:
        selectTime();
        break;
      default:
    }
  }

  ///报修时间选择
  selectTime() {
    EMILoding.showBottomWindow(
        RunMessageWidgets.seleDateWheelWidget(
            updataTime.isEmpty ? SPUtils.getTimeStr() : updataTime, (value) {
          Get.back();
          addRepairContent[2] = updataTime = value;
          update(['addRepair']);
        }),
        isDismissible: true,
        showBack: true);
  }

  inputChange() {
    if (addNewCT.text.length > 50) {
      var str = addNewCT.text.substring(0, 50);
      addNewCT.text = str;
    }
    update(['addRepair']);
  }

  ///网点确认
  selectSeverPoint() {
    Get.back();
    opintSelNum = opintSelTypeNum;
    addRepairContent[1] = pointList[opintSelNum].name ?? '';
    update(['addRepair']);
  }

  ///网点服务选择
  pointListSelect(int index) {
    opintSelTypeNum = index;
    selectPoint = pointList[index];
    update(['severList']);
  }

  ///获取车辆位置
  getMotoLocation() {
    RequestClient().post<Map<String, dynamic>>(APIS.getMotoMsg, data: {
      'ebike_id': selectData.id,
      'cmd': 'Location'
    }).then((value) async {
      var latLng =
          await EMIMapManger().convertLatLng(value?['lng'], value?['lat']);
      getServePointLocation(latLng);
    });
  }

  ///获取网点位置
  getServePointLocation(LatLng latLng) {
    RequestClient().post<ServePointData>(APIS.servePoint, data: {
      'coordinate': {'lat': latLng.latitude, 'lng': latLng.longitude}
    }).then((value) async {
      if (value != null) pointList = value.list!;
    });
  }
}
